//
//  FPNewsViewController.m
//  FilmParadise
//
//  Created by lanou3g on 15/7/13.
//  Copyright (c) 2015年 DLYgroup. All rights reserved.
//

#import "FPNewsViewController.h"
#import "FPNewsHeaderView.h"
#import "FPposterShowViewCell.h"
#import "FPIntroViewCell.h"
#import "FPHeaderModel.h"
#import "FPAnalysisHeader.h"
#import "FPIntroModel.h"
#import "FPWebViewController.h"
#import "FPHeadAanimation.h"
#import "FPAanimationModel.h"
@interface FPNewsViewController ()<UITableViewDelegate,UITableViewDataSource>
//顶部视图
@property(nonatomic,strong)FPNewsHeaderView *headerView;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *introArray;
@property(nonatomic,strong)NSArray *arrayAN;
@property(nonatomic,assign)BOOL isOver;
@property(nonatomic,assign)NSInteger pageIndex;
/**装载顶部模型数组*/
@property(nonatomic,strong)NSMutableArray *headerArray;
@end

@implementation FPNewsViewController


- (void)viewDidLoad {
    [super viewDidLoad];
  
    self.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.view.backgroundColor = [UIColor clearColor];
       [self creatTableView];
    [self tableViewPullDownLoad];
    [self tableviewPullUploadMore];
 
  }

//下拉加载
- (void)tableViewPullDownLoad
{
    __block typeof(self) BlockSelf = self;
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [BlockSelf analysisListData];
        [BlockSelf analysisHeaderViewData];
        [FPHeadAanimation analysisHA:BlockSelf.tableView];
    }];

    [self.tableView.header beginRefreshing];
    
}
//上啦加载更多
- (void)tableviewPullUploadMore
{
    __block typeof(self) BlockSelf = self;
    [self.tableView addGifFooterWithRefreshingBlock:^{
        [BlockSelf pullUPanalysis];
    }];
    NSMutableArray *imageArray = [[NSMutableArray alloc]init];
    for (int i = 2; i< 10; i ++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"catRefresh－%d（被拖移）.tiff",i]];
        [imageArray addObject:image];
    }
    [self.tableView.gifFooter setRefreshingImages:imageArray];
    self.tableView.footer.stateHidden = YES;
    
}
- (void)pullUPanalysis
{
    self.pageIndex += 1 ;
    NSString *str = [NSString stringWithFormat:@"http://api.m.mtime.cn/News/NewsList.api?pageIndex=%ld",self.pageIndex];
    NSURL *url = [NSURL URLWithString:str];
    //创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
    //开启异步联接 用队列的形式进行一步请求数据
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (!data)
        {
            return ;
        }
        //请求的所有数据已经全部接受完成的时候 ,才会执行Block快里的方法 此时data就是我们请求下来的数据它会自动传回到这个参数上面
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *newsLists = dic[@"newsList"];
        for (NSDictionary *smallDic in newsLists) {
            FPIntroModel *introModel = [FPIntroModel fpIntroModelWithDictionary:smallDic];
            
            introModel.IDStr = smallDic[@"id"];
            
            [self.introArray addObject:introModel];
        }
        [self.tableView reloadData];
        [self.tableView.footer endRefreshing];
    }];

}


//添加TableView
- (void)creatTableView
{
    UIView *view = [[UIView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:view];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64) style:UITableViewStylePlain];
    self.tableView.delegate =self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    self.headerView = [[FPNewsHeaderView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kImageH(150) + kImageH(30))];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickImage)];
    [self.headerView.picImageView addGestureRecognizer:tap];
    [self.headerView.introButton addTarget:self action:@selector(clickImage) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableHeaderView = _headerView ;

}
- (void)clickImage
{
    FPWebViewController *web = [[FPWebViewController alloc]init];
    FPHeaderModel *model = self.headerArray[0];
    web.stringURl = [NSString stringWithFormat:@"http://api.m.mtime.cn/News/Detail.api?newsId=%@",model.IDStr];
    NSLog(@"===%@",model.IDStr);
    [self.navigationController pushViewController:web animated:YES];
}

#pragma mark ====================解析顶部headerView数据
- (void)analysisHeaderViewData
{
    self.headerArray = [NSMutableArray array];
    if (![[FPNetWork shareInstance]rechability])
    {
        UIAlertView *aler = [[UIAlertView alloc]initWithTitle:nil message:@"无网络" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [aler show];
        return;
    }
  [LORequestManger GET:kHeaderURL success:^(id response) {
      NSDictionary *dic = (NSDictionary *)response;
      NSDictionary *newsDic = dic[@"news"];
      FPHeaderModel *newsHeaerModel = [FPHeaderModel fpNewsViewModeltSetValueWithDictionary:newsDic];
      newsHeaerModel.IDStr = newsDic[@"newsID"];
      [self.headerArray addObject:newsHeaerModel];
   
    [self.headerView.picImageView sd_setImageWithURL:[NSURL URLWithString:newsHeaerModel.imageUrl] placeholderImage:nil completed:nil];
      [self.headerView.introButton setTitle:newsHeaerModel.title forState:UIControlStateNormal];
      if ([newsHeaerModel.type integerValue] == 0)
      {
          self.headerView.rightImageView.hidden = YES;
      }
      else
      {
          self.headerView.rightImageView.hidden = NO;
 
      }
      [self.tableView reloadData];
      [self.tableView.header endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      NSLog(@"请求数据失败");
  }];

}

#pragma mark=====================解析列表数据
- (NSMutableArray *)introArray
{
    if (!_introArray)
    {
        _introArray = [NSMutableArray array];
    }
    return _introArray;
}
- (void)analysisListData
{
     self.pageIndex = 1;
    NSString *str = [NSString stringWithFormat:@"http://api.m.mtime.cn/News/NewsList.api?pageIndex=%ld",self.pageIndex];

    //    NSURL *url = [NSURL URLWithString:@"http://api.m.mtime.cn/News/NewsList.api?pageIndex=1"];
     NSURL *url = [NSURL URLWithString:str];
    //创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
    //开启异步联接 用队列的形式进行一步请求数据
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (!data)
        {
        return ;
        }
        //请求的所有数据已经全部接受完成的时候 ,才会执行Block快里的方法 此时data就是我们请求下来的数据它会自动传回到这个参数上面
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *newsLists = dic[@"newsList"];
        for (NSDictionary *smallDic in newsLists) {
            FPIntroModel *introModel = [FPIntroModel fpIntroModelWithDictionary:smallDic];
            
            introModel.IDStr = smallDic[@"id"];
           
            [self.introArray addObject:introModel];
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
    }];
}

#pragma mark ====================实现代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.introArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 
        static NSString *cellIndentifier = @"IntrlViewCell";
        [tableView registerClass:[FPIntroViewCell class] forCellReuseIdentifier:cellIndentifier];
        FPIntroViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier forIndexPath:indexPath];
        FPIntroModel *introModel = self.introArray[indexPath.row];
    
            [cell cellForModel:introModel];
        return cell;

    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        return 2 * kImageH(10) + kImageH(100);

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FPWebViewController *webVc = [[FPWebViewController alloc]init];
    self.hidesBottomBarWhenPushed = YES;
    FPIntroModel *model = self.introArray[indexPath.row];
   webVc.stringURl = [NSString stringWithFormat:@"http://api.m.mtime.cn/News/Detail.api?newsId=%@",model.IDStr];
    NSLog(@"=========%@",model.IDStr);
    [self.navigationController pushViewController:webVc animated:YES];
}




- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"cgClear"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.backgroundColor = [UIColor purpleColor];
    UIView *statusBarView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth , 20)];
    statusBarView.backgroundColor = [UIColor purpleColor];
    [self.view addSubview:statusBarView];
    [self.tabBarController.tabBar setHidden:NO];
    
}
@end
